<template>
  <div>
    <h1>用户健康信息</h1>
    <el-button color="#626aef" :dark="isDark" @click="openAddDialog">新增档案</el-button>

    <!-- 使用ElTable组件展示健康信息 -->
    <el-table :data="healthInfo" style="width: 100%">
      <el-table-column prop="healthName" label="姓名"></el-table-column>
      <el-table-column prop="idcard" label="身份证号"></el-table-column>
      <el-table-column label="性别" :formatter="genderFormatter"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="text" size="small" @click="viewDetails(scope.row)">查看详情</el-button>
          <el-button type="text" size="small" @click="editInfo(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="deleteInfo(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹出框 -->
    <el-dialog
        title="健康信息详情"
        v-model="dialogVisible"
        width="30%"
    >
      <div v-if="mode === 'view'">
        <el-form>
          <el-form-item label="姓名：" label-width="120">
            <el-input v-model="selectedHealthInfo.healthName" readonly></el-input>
          </el-form-item>
          <el-form-item label="身份证号：" label-width="120">
            <el-input v-model="selectedHealthInfo.idcard" readonly></el-input>
          </el-form-item>
          <el-form-item label="性别：" label-width="120">
            <el-tag :closable="false">
              {{ selectedHealthInfo.gender === 1 ? '男' : '女' }}
            </el-tag>
          </el-form-item>
          <el-form-item label="生日：" label-width="120">
            <el-input v-model="selectedHealthInfo.birthday" readonly></el-input>
          </el-form-item>
          <el-form-item label="身高：" label-width="120">
            <el-input v-model="selectedHealthInfo.height" readonly></el-input>
          </el-form-item>
          <el-form-item label="体重：" label-width="120">
            <el-input v-model="selectedHealthInfo.weight" readonly></el-input>
          </el-form-item>
          <el-form-item label="电话：" label-width="120">
            <el-input v-model="selectedHealthInfo.phone" readonly></el-input>
          </el-form-item>
          <el-form-item label="与您的关系：" label-width="120">
            <el-input v-model="selectedHealthInfo.relation" readonly></el-input>
          </el-form-item>
          <el-form-item label="既往病史：" label-width="120">
            <el-input v-model="selectedHealthInfo.anamnesis" readonly></el-input>
          </el-form-item>
          <el-form-item label="过敏史：" label-width="120">
            <el-input v-model="selectedHealthInfo.allergy" readonly></el-input>
          </el-form-item>
        </el-form>
      </div>

      <div v-else-if="mode === 'edit'">
        <el-form @submit.prevent="submitForm">
          <el-form-item label="姓名：" label-width="120">
            <el-input v-model="selectedHealthInfo.healthName"></el-input>
          </el-form-item>
          <el-form-item label="身份证号：" label-width="120">
            <el-input v-model="selectedHealthInfo.idcard"></el-input>
          </el-form-item>
          <el-form-item label="性别：" label-width="120">
            <el-radio-group v-model="selectedHealthInfo.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="生日：" label-width="120">
            <el-date-picker
                v-model="selectedHealthInfo.birthday"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-dd"
                value-format="YYYY-MM-dd"
                @change="handleDateChange">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="身高：" label-width="120">
            <el-input v-model="selectedHealthInfo.height"></el-input>
          </el-form-item>
          <el-form-item label="体重：" label-width="120">
            <el-input v-model="selectedHealthInfo.weight"></el-input>
          </el-form-item>
          <el-form-item label="电话：" label-width="120">
            <el-input v-model="selectedHealthInfo.phone"></el-input>
          </el-form-item>
          <el-form-item label="与您的关系：" label-width="120" v-if="mode === 'view'">
            <el-input v-model="selectedHealthInfo.relationText" readonly></el-input>
          </el-form-item>

          <!-- 编辑模式下的与您的关系 -->
          <el-form-item label="与您的关系：" label-width="120" v-else-if="mode === 'edit'">
            <el-select v-model="selectedHealthInfo.relation" placeholder="请选择">
              <el-option
                  v-for="(value, key) in relationMap"
                  :key="key"
                  :label="value"
                  :value="key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="既往病史：" label-width="120">
            <el-select v-model="selectedHealthInfo.anamnesis" placeholder="请选择">
              <el-option
                  v-for="item in anamnesisOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="过敏史：" label-width="120">
            <el-select v-model="selectedHealthInfo.allergy" placeholder="请选择">
              <el-option
                  v-for="item in allergyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 添加保存和取消按钮 -->
          <el-form-item>
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="cancelForm">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog
        title="新增健康信息"
        v-model="addDialogVisible"
        width="30%"
    >
      <el-form @submit.prevent="submitAddForm">
        <el-form-item label="姓名：" label-width="120">
          <el-input v-model="newHealthInfo.healthName"></el-input>
        </el-form-item>
        <el-form-item label="身份证号：" label-width="120">
          <el-input v-model="newHealthInfo.idcard"></el-input>
        </el-form-item>
        <el-form-item label="性别：" label-width="120">
          <el-radio-group v-model="newHealthInfo.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日：" label-width="120">
          <el-date-picker
              v-model="newHealthInfo.birthday"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-dd"
              value-format="YYYY-MM-dd"
              @change="handleDateChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="身高：" label-width="120">
          <el-input v-model="newHealthInfo.height"></el-input>
        </el-form-item>
        <el-form-item label="体重：" label-width="120">
          <el-input v-model="newHealthInfo.weight"></el-input>
        </el-form-item>
        <el-form-item label="电话：" label-width="120">
          <el-input v-model="newHealthInfo.phone"></el-input>
        </el-form-item>
        <el-form-item label="与您的关系：" label-width="120">
          <el-select v-model="newHealthInfo.relation" placeholder="请选择">
            <el-option
                v-for="(value, key) in relationMap"
                :key="key"
                :label="value"
                :value="key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="既往病史：" label-width="120">
          <el-select v-model="newHealthInfo.anamnesis" placeholder="请选择">
            <el-option
                v-for="item in anamnesisOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="过敏史：" label-width="120">
          <el-select v-model="newHealthInfo.allergy" placeholder="请选择">
            <el-option
                v-for="item in allergyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 添加保存和取消按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitAddForm">保存</el-button>
          <el-button @click="cancelAddForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import axios from 'axios';

export default {
  data() {
    return {
      healthInfo: [],
      userId: null,
      healthManageData: {},
      dialogVisible: false,
      addDialogVisible: false, // 新增弹窗的显示控制
      mode: 'view',
      selectedHealthInfo: {
        healthName: '',
        idcard: '',
        gender: 1,
        birthday: '',
        height: '',
        weight: '',
        phone: '',
        relation: null,
        anamnesis: null,
        allergy: null,
        relationText: '',
      },
      newHealthInfo: {
        healthName: '',
        idcard: '',
        gender: 1,
        birthday: '',
        height: '',
        weight: '',
        phone: '',
        relation: null,
        anamnesis: null,
        allergy: null
      },

      anamnesisOptions: [],
      allergyOptions: [],
      relationMap: {
        1: '子女',
        2: '兄弟姐妹',
        3: '祖孙关系',
        4: '夫妻关系',
      },
      isDark: false
    };
  },
  mounted() {
    this.userId = localStorage.getItem('userId');
    this.fetchHealthInfo();
    this.fetchAnamnesisOptions();
    this.fetchAllergyOptions();
  },
  methods: {
    openAddDialog() {
      this.dialogVisible = false; // 关闭详情或编辑弹窗
      this.addDialogVisible = true; // 打开新增弹窗
      this.mode = 'add';
      this.newHealthInfo = {
        healthName: '',
        idcard: '',
        gender: 1,
        birthday: '',
        height: '',
        weight: '',
        phone: '',
        relation: null,
        anamnesia: null,
        allergy: null,
        userId:this.userId
      };
      this.fetchAnamnesisOptions();
      this.fetchAllergyOptions();
    },
    checkIdCardExists(idCard) {
      return new Promise((resolve, reject) => {
        axios.get('check-idcard-exists', {
          params: { idcard: idCard }
        }).then(response => {
          if (response.data && response.data.code === 200) {
            resolve(response.data.data);
          } else {
            reject('检查身份证号时发生错误');
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    submitAddForm() {
      if (this.newHealthInfo.idcard.length !== 18) {
        this.$message.error('身份证号必须为18位，请重新输入。');
        return; // 退出函数，阻止表单提交
      }

      // 验证电话号码是否至少为4位
      if (this.newHealthInfo.phone.length !== 11) {
        this.$message.error('电话号码至少为4位，请重新输入。');
        return; // 退出函数，阻止表单提交
      }
      // 首先检查身份证号是否已存在
      this.checkIdCardExists(this.newHealthInfo.idcard).then(exists => {
        if (exists) {
          // 如果身份证号已存在，显示错误消息并阻止表单提交
          this.$message.error('该身份证号已存在，请使用其他身份证号。');
        } else {
          // 如果身份证号不存在，继续提交表单
          const healthManageData = {
            healthName: this.newHealthInfo.healthName,
            idcard: this.newHealthInfo.idcard,
            gender: this.newHealthInfo.gender,
            birthday: this.newHealthInfo.birthday,
            height: this.newHealthInfo.height,
            weight: this.newHealthInfo.weight,
            phone: this.newHealthInfo.phone,
            relation: this.newHealthInfo.relation,
            anamnesisid: this.newHealthInfo.anamnesis,
            allergyid: this.newHealthInfo.allergy,
            userid: this.userId
          };
          console.log(healthManageData);
          axios.post(`/hospital-health-add`, healthManageData)
              .then(response => {
                console.log(response)
                if (response.data && response.data.code === 200) {
                  this.addDialogVisible = false;
                  this.fetchHealthInfo(); // 重新获取健康信息
                  this.$message.success(response.data.msg || '新增成功');
                } else {
                  console.error('新增失败:', response.data ? response.data.msg : '未知错误');
                  this.$message.error(response.data ? response.data.msg : '新增失败');
                }
              })
              .catch(error => {
                console.error('Error adding health info:', error);
                this.$message.error('添加健康信息时发生错误');
              });
        }
      }).catch(error => {
        console.error('Error checking ID card:', error);
        this.$message.error('检查身份证号时发生错误，请稍后再试。');
      });
    },
    cancelAddForm() {
      this.addDialogVisible = false;
    },

    submitForm() {
      if (this.selectedHealthInfo.idcard.length !== 18) {
        this.$message.error('身份证号必须为18位，请重新输入。');
        return; // 退出函数，阻止表单提交
      }

      // 验证电话号码是否至少为4位
      if (this.selectedHealthInfo.phone.length !== 11) {
        this.$message.error('电话号码应该为11位，请重新输入。');
        return; // 退出函数，阻止表单提交
      }
      const healthInfoData = {
        allergyid: this.selectedHealthInfo.allergyid,
        anamnesisid: this.selectedHealthInfo.anamnesisid,
        birthday: this.selectedHealthInfo.birthday,
        gender: this.selectedHealthInfo.gender,
        healthName: this.selectedHealthInfo.healthName,
        height: this.selectedHealthInfo.height,
        idcard: this.selectedHealthInfo.idcard,
        phone: this.selectedHealthInfo.phone,
        relation: this.selectedHealthInfo.relation,
        userid: this.userId, // 假设您已经从localStorage获取了userId
        weight: this.selectedHealthInfo.weight
      };

      // 发送PUT请求到后端更新接口
      axios.put(`/hospital-health-update/${this.selectedHealthInfo.id}`, healthInfoData)
          .then(response => {
            if (response.data.code === 200) {
              // 更新成功的处理
              this.dialogVisible = false; // 关闭对话框
              this.fetchHealthInfo(); // 重新获取健康信息
              this.$message.success(response.data.msg); // 显示成功消息
            } else {
              // 处理错误情况
              console.error('更新失败:', response.data.message);
              this.$message.error(response.data.msg); // 显示错误消息
            }
          })
          .catch(error => {
            // 处理请求错误
            console.error('Error updating health info:', error);
            this.$message.error('更新健康信息时发生错误'); // 显示错误消息
          });
    },
    cancelForm() {
      // 处理取消逻辑
      console.log('取消操作');
      // 例如，重置表单或关闭弹出框
    },
    fetchHealthInfo() {
      if (this.userId) {
        axios.get(`/hospital-health?id=${this.userId}`)
            .then(response => {
              console.log(response.data)
              console.log('获取健康信息')
              if (response.data.code === 200 && response.data.data && response.data.data.length > 0) {
                this.healthInfo = response.data.data;
              } else {
                console.error('没有找到数据');
              }
            })
            .catch(error => {
              console.error('Error fetching health info:', error);
            });
      } else {
        console.error('用户ID未找到');
      }
    },
    fetchAnamnesisOptions() {
      axios.get('/health-anamnesis-all')
          .then(response => {
            if (response.data.code === 200 && response.data.data) {
              this.anamnesisOptions = response.data.data.map(item => ({
                label: item.disease, // 确保这里的字段与后端返回的字段匹配
                value: item.anamnesis, // 确保这里的字段与后端返回的字段匹配
              }));
            } else {
              console.error('没有找到既往病史数据');
            }
          })
          .catch(error => {
            console.error('Error fetching anamnesis options:', error);
          });
    },
    fetchAllergyOptions() {
      axios.get('/health-allergy-all')
          .then(response => {
            console.log(response)
            if (response.data.code === 200 && response.data.data) {
              this.allergyOptions = response.data.data.map(item => ({
                label: item.allergy, // 假设后端返回的过敏名称字段是 allergyName
                value: item.allergyid, // 假设每个过敏的标识符是 id
              }));
            } else {
              console.error('没有找到过敏史数据');
            }
          })
          .catch(error => {
            console.error('Error fetching allergy options:', error);
          });
    },

    genderFormatter(row) {
      return row.gender === 1 ? '男' : '女';
    },
    viewDetails(row) {
      this.mode = 'view';
      this.selectedHealthInfo = Object.assign({}, row);
      this.selectedHealthInfo.relation = this.relationMap[this.selectedHealthInfo.relation] || '未知关系'; // 设置关系描述
      this.dialogVisible = true;
      this.fetchAllergy();
      this.fetchAnamnesis();
    },

    editInfo(row) {
      this.mode = 'edit';
      this.selectedHealthInfo = Object.assign({}, row);
      // 从relationMap中找到对应的文字描述，并设置到relationText
      this.selectedHealthInfo.relationText = this.relationMap[this.selectedHealthInfo.relation] || '未知关系';
      // 同时设置relation为数字ID，以便与下拉列表的v-model同步
      this.selectedHealthInfo.relation = this.selectedHealthInfo.relation.toString();
      this.dialogVisible = true;
      this.fetchAllergy();
      this.fetchAnamnesis();
    },
    fetchAllergy() {
      axios.get(`/health-allergy?id=${this.selectedHealthInfo.allergyid}`)
          .then(response => {

            if (response.data.code === 200 && response.data.data && response.data.data.length > 0) {
              this.selectedHealthInfo.allergy = response.data.data[0].allergy;
            } else {
              this.selectedHealthInfo.allergy = '无过敏史';
            }
          })
          .catch(error => {
            console.error('Error fetching allergy:', error);
            this.selectedHealthInfo.allergy = '无过敏史';
          });
    },
    fetchAnamnesis() {
      axios.get(`/health-anamnesis?id=${this.selectedHealthInfo.anamnesisid}`)
          .then(response => {
            if (response.data.code === 200 && response.data.data && response.data.data.length > 0) {
              const diseaseInfo = response.data.data[0];
              this.selectedHealthInfo.anamnesis = diseaseInfo.disease; // 使用 disease 字段
            } else {
              this.selectedHealthInfo.anamnesis = '无既往病史';
            }
          })
          .catch(error => {
            console.error('Error fetching anamnesis:', error);
            this.selectedHealthInfo.anamnesis = '无既往病史';
          });
    },

    deleteInfo(row) {
      // 处理删除的逻辑
      console.log('删除:', row);
      // 确认步骤
      this.$confirm('确认删除这条健康信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        axios.delete(`/hospital-health-delete/${row.id}`)
            .then(response => {
              console.log(response);
              if (response.data && response.data.code === 200) {
                this.$message.success(response.data.msg || '删除成功');
                // 刷新列表或执行其他逻辑
                this.fetchHealthInfo(); // 假设这是刷新列表的方法
              } else {
                this.$message.error(response.data.msg || '删除失败');
              }
            })
            .catch(error => {
              console.error('Error deleting health info:', error);
              this.$message.error('删除健康信息时发生错误');
            });
      }).catch(() => {
        // 取消删除
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
};
</script>

<style>

</style>